package com.ccteam.fluidmusic.utils

import android.content.Context
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.ActivityResultRegistry
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.orhanobut.logger.Logger

/**
 * @author Xiaoc
 * @since 2021/2/19
 *
 * 权限申请处理器
 * @param context 为Toast做准备，建议为 applicationContext
 * @param registry 对应Activity的ResultRegistry注册器
 * @param isForeverDenied lambda 表达式，判断当前权限是否被永久禁止
 * @param grantPermissionsAction 当权限申请通过后的操作
 */
class PermissionHandler(
    private val context: Context,
    private val registry: ActivityResultRegistry,
    private val isForeverDenied: (String) -> Boolean,
    private val grantPermissionsAction: () -> Unit): DefaultLifecycleObserver {

    private lateinit var permissionRequestLauncher: ActivityResultLauncher<Array<String>>

    override fun onCreate(owner: LifecycleOwner) {
        permissionRequestLauncher = registry.register("permissionRequest",owner,
            ActivityResultContracts.RequestMultiplePermissions()){ result ->

            result.forEach{
                if(!it.value){
                    if(isForeverDenied(it.key)){
                        // TODO
                        Logger.d("跳转权限设置")
                    }
                    Toast.makeText(context,"权限被禁止",Toast.LENGTH_SHORT).show()
                    return@register
                }
            }
            Logger.d("权限允许")
            grantPermissionsAction()
        }
    }

    /**
     * 权限申请
     * @param permissions 需要申请的权限数组
     */
    fun permissionRequest(permissions: Array<String>){
        permissionRequestLauncher.launch(permissions)
    }
}